package com.island.practice.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedHashSet;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.island.practice.entity.Role;

public class ListRoleServlet extends AbstractServlet{
	
	private static final String SQL_QUERY_ROLE = "SELECT * FROM ROLE";

	protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
			
		Set<Role> roles = new LinkedHashSet<Role>();
    	Role role = null;
    	Connection connection = null;
    	PreparedStatement statement4Role = null;
    	ResultSet roleResults = null;
    	
    	try {
			connection = this.getConnection();
			statement4Role = connection.prepareStatement(SQL_QUERY_ROLE);
			roleResults = statement4Role.executeQuery();
	    	
	    	while(roleResults.next()){
	    		role = new Role();
	    		role.setRoleId(roleResults.getString("ROLE_ID"));
	    		role.setRoleName(roleResults.getString("ROLE_NAME"));
	    			    		
	    		
	    		roles.add(role);
	    	}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("get roles failed", e);
		} finally {
			closeStatement(statement4Role);
			closeConnection(connection);
		}
    	
    	request.setAttribute("roleList",roles);
        //Forward to the jsp page for rendering		
		request.getRequestDispatcher("/Role/ListRole.jsp").forward(request, response);
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
		    throws ServletException, IOException {		
		        processRequest(request, response);
		    }
		    
		    /** Handles the HTTP <code>POST</code> method.
		     * @param request servlet request
		     * @param response servlet response
		     */
		    protected void doPost(HttpServletRequest request, HttpServletResponse response)
		    throws ServletException, IOException {
		        processRequest(request, response);
		    }

}
